package com.songshan.filter;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.songshan.bean.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;

import java.util.Date;
import java.util.UUID;

/**
 * @author feb
 * @date 2024/6/18
 * @Description: token生成和解析工具
 */
public class JWTUtil {

  private static Logger log = LoggerFactory.getLogger(JWTUtil.class);

  public static String generateToken(User user) {
    return JWT.create()
        .withJWTId(new BASE64Encoder().encode(UUID.randomUUID().toString().getBytes()))
        .withSubject(user.getId().toString())
        .withClaim("userInfo", JSONObject.toJSONString(user))
        //过期时间60分钟
        .withExpiresAt(DateUtil.offsetMinute(new Date(), 60))
        .sign(Algorithm.HMAC256("authKey"));
  }

  public static User parseToken(String token, boolean refresh) {
    try {
      DecodedJWT dj = JWT.require(Algorithm.HMAC256("authKey")).build().verify(token);
      User user = JSONObject.parseObject(dj.getClaim("userInfo").asString(), User.class);
      if (refresh) {
        token = generateToken(user);
      }
      user.setToken(token);
      return user;
    } catch (Exception e) {
      log.info("token解析失败："+e.getMessage());
    }
    return null;
  }
}
